package com.guochao.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guochao.entity.ClassIfication;
import com.guochao.entity.Product;
import com.guochao.entity.Size;
import com.guochao.service.ClassificationService;
import com.guochao.service.LoginService;
import com.guochao.service.ProductService;
import com.guochao.util.ReturnMsg;
import com.guochao.util.ToolsUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/adminproduct")
public class AdminProductController {

    @Resource
    private ProductService productSvc;

    @Resource
    private LoginService loginSvc;

    @Resource
    private ClassificationService cIficationSvc;

    /**
     * 商品列表
     */
    @ResponseBody
    @RequestMapping(value = "getHotList", produces = "application/json;charset=UTF-8")
    public Map<String, Object> getHotList() {
        Map<String, Object> map = new HashMap<String, Object>();
        /* selTypePro参数含义：按照库存搜索 3 个商品进行升序查询，库存最多的为当前最火热系列*/
        List<Product> list = productSvc.selTypePro("stock", 3, "DESC");
        map.put("my_pro_list", list);
        return map;
    }


    @RequestMapping("/products")
    @ResponseBody
    public ReturnMsg getUnits(@RequestParam(value = "pn", defaultValue = "1") Integer pn,
                              HttpSession session, HttpServletRequest request) {

        //引入PageHelper分页插件
        //在查询之前只需要传入页码以及每页的大小
        PageHelper.startPage(pn, 5);
        //startPage方法紧跟第一个select查询就是一个分页查询
        List<Product> product = productSvc.selProductAll();
        //使用PageInfo包装查询结果，封装了分页信息和查询出的数据，只需将pageInfo交给页面即可
        PageInfo pageInfo = new PageInfo(product, 5);

        return ReturnMsg.success().add("pageInfo", pageInfo);
    }


    /**
     * 管理员页面：显示商品列表
     */
    @ResponseBody
    @RequestMapping(value = "productlist", produces = "application/json;charset=UTF-8")
    public Map<String, Object> prodectList() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Product> list = productSvc.selProductAll();
        map.put("pro_all_list", list);
        return map;
    }

    /**
     * 显示后台主页的热门商品*6
     */
    @ResponseBody
    @RequestMapping(value = "prolistcount", produces = "application/json;charset=UTF-8")
    public Map<String, Object> proListCount() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Product> list = productSvc.selNumProduct(6);
        map.put("my_list", list);
        return map;
    }

    /**
     * 管理员页面：显示商品信息
     */
    @RequestMapping(value = "proalter")
    public String amdSelUserByID(
            Integer pid,
            HttpServletRequest request) {
        Product product = productSvc.proSelByCId(pid);
        List<ClassIfication> list = cIficationSvc.selAllClass();
        request.setAttribute("adm_proinfo", product);
        request.setAttribute("adm_classlist", list);
        return "backstage/pro_alter";
    }

    /**
     * 管理员页面：修改商品信息
     */
    @ResponseBody
    @RequestMapping(value = "admUpProduct", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public Map<String, Object> admUpProduct(Product product, @RequestParam(value = "file", required = false) MultipartFile profile, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        Product pro_info = productSvc.proSelByCId(product.getPid());
        System.out.println(pro_info);
        System.out.println(pro_info.getSize());
        if (profile != null) {
            String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "upprodectimg");//文件上传后保存到的服务器路径，File.separator是路径分隔符（\）
            String res = ToolsUtil.upPic(path, profile, pro_info);
            if (res != null) {
                map.put("upError", res);
                return map;
            }
        }
        System.out.println("por"+product);
        System.out.println("pname"+product.getPname());
        System.out.println("stock"+product.getStock());
//        System.out.println("size"+product.getSize());
        if (!("").equals(product.getPname())) {
            pro_info.setPname(product.getPname());
        }

        if (!("").equals(product.getTitle())) {
            pro_info.setTitle(product.getTitle());
        }
        if (!("").equals(product.getDescb())) {
            pro_info.setDescb(product.getDescb());
        }
        if (product.getClassid() != null) {
            pro_info.setClassid(product.getClassid());
        }
        if (product.getPrice() != null) {
            pro_info.setPrice(product.getPrice());
        }
        if (product.getStock() != null) {
            pro_info.setStock(product.getStock());
        }

        if (product.getStockS() != null) {
            pro_info.setStockS(product.getStockS());
        }

        if (product.getStockM() != null) {
            pro_info.setStockM(product.getStockM());
        }

        if (product.getStockL() != null) {
            pro_info.setStockL(product.getStockL());
        }
        System.out.println(product.getStockS());
        System.out.println(product.getStockL());
        System.out.println(product.getStockM());

//        if (size.get(1).getStock()!=null) {//S码库存
//            pro_info.setStock(product.getStock());
//        }
//        if (size.get(2).getStock()!=null) {//M码库存
//        }
//        if (size.get(3).getStock()!=null) {//L码库存
//        }


        int i = productSvc.upProduct(pro_info);
        map.put("adm_upres", i);
        return map;
    }

    /**
     * 商品添加
     */
    @ResponseBody
    @RequestMapping(value = "addProduct", produces = "application/json;charset=UTF-8")
    public Map<String, Object> addProduct(
            Product product,
            @RequestParam(value = "addfile", required = false) MultipartFile addfile,
            HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();

        if (addfile != null) {
            String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "upprodectimg");
            String add_res = ToolsUtil.upPic(path, addfile, product);
            if (add_res != null) {
                System.out.println("文件上传失败");
                map.put("upError", add_res);
                return map;
            }
        } else {
            product.setPimg("1572611601955_Product.jpg");
        }
        product.setBytime(ToolsUtil.getTime("yyyy-MM-dd HH:mm:ss", 0));
        System.out.println("添加商品："+product);
        int i = productSvc.addProduct(product);
        map.put("resI", i);
        return map;
    }

    /**
     * 商品删除
     */
    @ResponseBody
    @RequestMapping(value = "delProduct", produces = "application/json;charset=UTF-8")
    public Map<String, Object> delProduct(
            Integer pid) {
        Map<String, Object> map = new HashMap<String, Object>();
        int i = productSvc.delProduct(pid);
        map.put("delPro_res", i);
        return map;
    }

    /**
     * 商品删除
     */
    @RequestMapping(value = "/delProducts/{ids}", method = RequestMethod.DELETE)
    @ResponseBody
    public ReturnMsg delProducts(@PathVariable("ids") String ids) {

        if (productSvc.delProducts(ids)) {
            return ReturnMsg.success();
        }
        return ReturnMsg.fail();
    }
}
